<?php
require_once '../data/data.php';

// 开启session
session_start();

// 只支持POST请求，否则返回405错误
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
   header('HTTP/1.1 405 Method Not Allowed');
   return;
}

// 获取请求中的用户输入数据
$userName = isset($_POST['username']) ? htmlspecialchars($_POST['username']) : '';
$password = isset($_POST['password']) ? htmlspecialchars($_POST['password']) : '';

$hasError = true;
$errorBag['error'] = '用户名或密码错误';

if (trim($userName) == '' || $password == '') {
  $hasError = true;
  $errorBag['error'] = '用户名密码不得为空';
}

// 判断用户是否勾选了记住我
$rememberMe = isset($_POST['remember-me']) && $_POST['remember-me'] == 1;
  
// 根据用户名查找用户记录
$sql = 'select id,user_name,password from users where user_name=?';
$data = query($sql, [$userName]);
if (count($data) > 0) {
  // 用户名正确，会查询到用户记录，则验证密码
  $user = $data[0];
  if (password_verify($password, $user['password'])) {
    // 密码正确, 做登录正确的处理
    $hasError = false;
    // 修改登录时间和ip
    $ip = $_SERVER['REMOTE_ADDR'];

    // 判断是否勾选了记住我自动登录，若记住我，则生成remember-token
    if ($rememberMe === true) {
      $tmp = md5($user['id'] . time() . mt_rand());
      // 自动登录令牌存入cookie
      $rememberToken = md5(substr($tmp, 3, 16));

      $salt = hash('sha256', uniqid() . mt_rand());
      // 加密自动登录令牌，要存入数据库
      $seToken = hash('sha256', $rememberToken . $salt);
      // 把记住我的令牌通过一次性session信息发送到要重定向的页面去发送cookie
      $_SESSION['remember-token'] = $rememberToken;
      // 把remember-token写入数据库users表
      $sql = 'update users set last_login=now(),last_login_ip=?,remember_token=?, token_salt=? where id=?';
      $args = [$ip, $seToken, $salt, $user['id']];
    } else {
      $sql = 'update users set last_login=now(),last_login_ip=? where id=?';
      $args = [$ip, $user['id']];
    }
  
    execute($sql, $args);
    // 用户名密码验证通过，把用户信息存入session，意味已登录
    $_SESSION['user'] = $user;
    header('Location:../index.php');
    return;
  }
}

// 将错误包写入session
if ($hasError) {
   $_SESSION['has_error'] = $hasError;
   $_SESSION['error_bag'] = $errorBag;
   header('Location:../signin.php');
}
